(function($, com) {
	var gen_compressed = false;
	var PUBLIC_KEY_VERSION = 0;
	var PRIVATE_KEY_VERSION = 0x80;

	

	//scrypt parameters
	var logN = 18;
	var r = 8;
	var L = 32;
	var step = 2048; //iterations per step

	function pad(str, len, ch) {
		padding = '';
		for(var i = 0; i < len - str.length; i++) {
			padding += ch;
		}
		return padding + str;
	}

	function getEncoded(pt, compressed) {
		var x = pt.getX().toBigInteger();
		var y = pt.getY().toBigInteger();
		var enc = integerToBytes(x, 32);
		if(compressed) {
			if(y.isEven()) {
				enc.unshift(0x02);
			} else {
				enc.unshift(0x03);
			}
		} else {
			enc.unshift(0x04);
			enc = enc.concat(integerToBytes(y, 32));
		}
		return enc;
	}

	function makeAddr(phr) {
		var hash = Crypto.SHA256(phr, {
			asBytes: true
		});
		hash = Crypto.util.bytesToHex(hash);
		var hash_str = pad(hash, 64, '0');
		var hash = Crypto.util.hexToBytes(hash_str);
		eckey = new Bitcoin.ECKey(hash);
		gen_eckey = eckey;
		var curve = getSECCurveByName("secp256k1");
		gen_pt = curve.getG().multiply(eckey.priv);
		gen_eckey.pub = getEncoded(gen_pt, gen_compressed);
		gen_eckey.pubKeyHash = Bitcoin.Util.sha256ripe160(gen_eckey.pub);
		var eckey = gen_eckey;
		var compressed = gen_compressed;
		var hash160 = eckey.getPubKeyHash();
		var h160 = Crypto.util.bytesToHex(hash160);
		var addr = new Bitcoin.Address(hash160);
		addr.version = PUBLIC_KEY_VERSION;

		var payload = hash;
		if(compressed)
			payload.push(0x01);
		var sec = new Bitcoin.Address(payload);
		sec.version = PRIVATE_KEY_VERSION;
		return {
			"address": addr.toString(),
			"sec": sec.toString()
		};

	}
	com.getWord = function() {
		var pk = secureRandom(32);
		var seed = Crypto.util.bytesToHex(pk.slice(0, 16));
		//nb! electrum doesn't handle trailing zeros very well
		if(seed.charAt(0) == '0') seed = seed.substr(1);
		return mn_encode(seed);
	};
	com.createWallet = function(passphrase, salt, func) {
		scrypt(passphrase, salt, {
		    N: 262144,
		    r: 8,
		    p: 1,
		    dkLen: 32,
		    encoding: 'hex'
		}, function(result) {
			rt = makeAddr(result);
		    func(rt);
		});
		/*
		scrypt(passphrase, salt, logN, r, L, step,
			function(progress) {
				//console.log(progress);
			},
			function(result) {
				rt = makeAddr(result);
				console.log(rt.address);
				func(rt);
			},
			"hex");*/
	}
	com.getBalance = function(addr, func){
		var url = 'https://chain.api.btc.com/v3/address/' + addr;
		//console.log(addr);
		$.getJSON(url, function(res){
			//console.log(JSON.stringify(res));
			if(res.err_no == 0 && res.data) {
				res.data.money = res.data.balance/100000000; 
				return func(res.data);
			}
		});
	};
}(mui, window.bitscan = {}));